import os
import random
import subprocess
import time
import requests
import traceback

import numpy
from loguru import logger
from playwright.sync_api import sync_playwright
import single_login


class ChenFeng:
    def __init__(self, playwright, host, command):
        self.playwright = playwright
        self.host = host
        self.command = command
        self.login_func = single_login.Login(playwright, host, command)
        self.download_path = os.path.join(os.getcwd(), "download")
        if not os.path.exists(self.download_path):
            os.mkdir(self.download_path)


    def run(self):
        # 所有文件的路径列表
        all_file_path_list = []
        self.login_func.login()
        self.click_kucun_button()
        logger.info("点击【实时业务库存查询】按钮...")
        self.login_func.page.query_selector('a:has-text("实时业务库存查询")').click()
        self.wait(self.login_func.page)
        logger.info('等待20秒页面加载完成...')
        for i in range(20):
            logger.info('【{}】秒【20】秒'.format(i + 1))
            time.sleep(1)
            logger.info("检查是否弹窗遮住了按钮...")
            if self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]') is not None and \
                    self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').is_visible():
                logger.info("弹窗遮住了按钮...")
                self.login_func.page.query_selector('//div[contains(@class, "aes-survey-page--close")]').click()
        logger.info("找到【供应商名称】所在的索引...")
        found_carrier = False
        carrier_list = []
        # 找到供应商名称所在的索引
        carrier_selector = None
        div_list = self.login_func.page.query_selector_all('//div[contains(@class, "next-form-item")]')
        for i in range(len(div_list)):
            text = div_list[i].inner_text()
            if len(text) < 16 and "供应商名称" in text:
                carrier_selector = div_list[i].query_selector('input')
                carrier_selector.click()
                time.sleep(2)
                logger.info("获取供应商所有下拉数据...")
                li_list = self.login_func.page.query_selector('[role="listbox"]').query_selector_all('li')
                for j in range(len(li_list)):
                    carrier_list.append(li_list[j].inner_text())
                found_carrier = True
                break
        if not found_carrier:
            logger.error("没有找到【供应商名称】所在的索引...")
            return
        logger.info('正在下载实时业务库存数据...')
        self.download_sskc(carrier_list, carrier_selector, all_file_path_list)
        logger.info("所有实时业务库存数据下载完成...")

    def click_kucun_button(self):
        self.wait(self.login_func.page)
        for i in range(30):
            if self.login_func.page.query_selector('ul.nav-menu-list') is not None and self.login_func.page.query_selector('ul.nav-menu-list').is_visible():
                logger.info("页面加载完成...")
                break
            else:
                logger.info("等待页面加载完成【{}】秒【{}】秒".format(30, i + 1))
            time.sleep(1)
        # 点击【库存】按钮
        ul = self.login_func.page.query_selector('ul.nav-menu-list')
        li_list = ul.query_selector_all('li')
        # 是否点击库存标识
        has_click_kucun = False
        for i in range(len(li_list)):
            if "库存" == li_list[i].inner_text() and li_list[i].is_visible():
                li_list[i].click()
                has_click_kucun = True
                break
        if not has_click_kucun:
            logger.error("没有找到【库存】按钮...")
            logger.info("尝试点击【更多】按钮...")
            # 是否点击更多按钮
            has_click_more = False
            for i in range(len(li_list)):
                if li_list[i] is not None and \
                        li_list[i].inner_text() is not None and \
                        li_list[i].inner_text().startswith("更多"):
                    li_list[i].click()
                    time.sleep(1)
                    has_click_more = True
                    break
            if has_click_more:
                li_list = self.login_func.page.query_selector('ul.nav-more').query_selector_all('li')
                for i in range(len(li_list)):
                    if "库存" == li_list[i].inner_text():
                        li_list[i].click()
                        has_click_kucun = True
                        break
        if not has_click_kucun:
            logger.error("没有找到【库存】按钮...")
            self.close()
            return
        self.wait(self.login_func.page)


    def download_sskc(self, carrier_list, carrier_selector, all_file_path_list):
        for i in range(len(carrier_list)):
            try:
                self.click_carrier(i, carrier_selector)
                carrier_name = carrier_list[i]
                logger.info("正在操作第{}个供应商：{}".format(i + 1, carrier_name))
                logger.info("先点击【查询】按钮查询数据...")
                with self.login_func.page.expect_response("*aic-report/queryAicInventory*") as response_info:
                    self.login_func.page.query_selector_all('[type="submit"]')[1].click()
                    self.wait(self.login_func.page)
                # 点击【导出】按钮
                time.sleep(2)
                self.login_func.page.query_selector('button:has-text("导出")').click()
                logger.info("点击【导出】按钮...")
                with self.login_func.page.expect_response("*aic-report/createExportTask") as response_info:
                    self.login_func.page.query_selector('[role="listbox"]').query_selector_all('li')[1].click()
                    logger.info("点击【全部】按钮...")
                self.wait(self.login_func.page)
                time.sleep(5)
                logger.info("等待【导出 实时库存】弹窗出现...")
                for j in range(60):
                    ul = self.login_func.page.query_selector('//ul[contains(@class, "river-notification-center_list_uicontainer")]')
                    if ul is None or not ul.is_visible():
                        time.sleep(1)
                        continue
                    li_list = self.login_func.page.query_selector('//ul[contains(@class, "river-notification-center_list_uicontainer")]').query_selector_all('li')
                    first_li = li_list[0]
                    if first_li.query_selector('a') is None or not first_li.query_selector('a').is_visible():
                        time.sleep(1)
                        continue
                    with self.login_func.page.expect_download() as download_info:
                        a_box = first_li.query_selector('a').bounding_box()
                        first_li.query_selector('a').click()
                    download = download_info.value
                    file_path = os.path.join(os.getcwd(), "sskc_download")
                    if not os.path.exists(file_path):
                        os.mkdir(file_path)
                    file_path = os.path.join(file_path, carrier_name + ".xlsx")
                    if os.path.exists(file_path):
                        os.remove(file_path)
                    download.save_as(file_path)
                    all_file_path_list.append(file_path)
                    self.upload_file(file_path)
                    logger.info("点击其他地方关闭下载窗口...")
                    self.login_func.page.mouse.click((a_box["x"] + a_box["width"] / 2) - 600, a_box["y"] + a_box["height"] / 2)
                    break
                self.login_func.page.query_selector('button:has-text("重置")').click()
                logger.info("点击【重置】按钮...")
                # 获取文件名
            except Exception as e:
                logger.error("操作第{}个供应商：{}，失败，原因：{}".format(i + 1, carrier_list[i], e))
                continue

    def click_carrier(self, i, carrier_selector):
        ul = self.login_func.page.query_selector('[role="listbox"]')
        if ul is None or not ul.is_visible():
            carrier_selector.click()
            ul_list = self.login_func.page.query_selector_all('[role="listbox"]')
            for ul_item in ul_list:
                if ul_item.is_visible():
                    ul = ul_item
                    break
            time.sleep(2)
        li_list = ul.query_selector_all('li')
        li_list[i].click()

    def upload_file(self, file_path):
        try:
            logger.info("正在上传文件到服务器：" + file_path)
            url = self.host + "/onwayInventory/sysOnwayInventoryImport"
            files = [
                ('file', (open(file_path, 'rb')))
            ]
            response = requests.request("POST", url, files=files)
            logger.info(response.text)
        except:
            traceback.print_exc()

    def wait(self, page, seconds=1):
        page.wait_for_load_state(state="domcontentloaded")
        time.sleep(seconds)

    def close(self):
        try:
            if self.login_func.page:
                self.login_func.page.close()
        except:
            pass
        try:
            if self.login_func.browser:
                self.login_func.browser.close()
        except:
            pass
        try:
            if self.login_func.context:
                self.login_func.context.close()
        except:
            pass

def main(host, command):
    with sync_playwright() as playwright:
        for i in range(6):
            try:
                chen_feng = ChenFeng(playwright, host, command)
                chen_feng.run()
                chen_feng.close()
                return True
            except:
                traceback.print_exc()
    return False


# main()
